import { login, getUserinfo, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken, setTokenTime, getTime, removeTokenTime } from '@/utils/auth'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken(), // 设置token为共享的状态，初始化vuex的数据，就先从缓存中获取
    userinfo: {},
    startTokenTime: getTime()
  },
  mutations: {
    setToken(state, token) {
      state.token = token // 将数据设置给vuex
      setToken(token)// 同步给缓存
    },
    removeToken(state) {
      state.token = null // 将vuex的数据置空
      removeToken() // 同步给缓存
    },
    removeUserinfo(state) {
      state.userinfo = {}
    },
    setStartTokenTime(state, time) {
      state.startTokenTime = time
      setTokenTime(time)
    },
    removeStartTokenTime(state) {
      state.startTokenTime = null
      removeTokenTime()
    },
    setUserinfo(state, userinfo) {
      state.userinfo = userinfo
    }
  },
  actions: {
    //  发送登录请求
    async login({ commit }, userinfo) {
      // console.log(userinfo)
      // return new Promise((resolve, reject) => {
      //   login(userinfo)
      //     .then(res => {
      //       if (res.status === 200) {
      //         commit('setToken', res.data.data)
      //       }
      //     })
      // })
      const res = await login(userinfo)
      if (res.success) {
        commit('setToken', res.data)
      }
    },
    // 发送获取用户信息
    async getUserprofile({ commit }) {
      const res = await getUserinfo()
      const res1 = await getUserDetailById(res.data.userId)
      const userinfo = { ...res.data, ...res1.data }
      commit('setUserinfo', userinfo)
      return res.data
    },
    logout({ commit }) {
      commit('removeToken')
      commit('removeUserinfo')
      commit('removeStartTokenTime')
      // 退出登录后，清空路由 将原来动态挂载的路由全部清空
      resetRouter()
      // 退出登录后，清空菜单 清空vuex中的菜单 如何在user模块中调 用permission模块的mutations？
      commit('permission/setRouter', [], { root: true })
    }
  }
}
